package com.infotel.prefecture.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

import com.infotel.prefecture.exception.PrefectureException;
import com.infotel.prefecture.model.Particulier;
import com.infotel.prefecture.model.Proprietaire;
import com.infotel.prefecture.model.Societe;

public class ProprietaireDAOJdbc extends AbstractDAOJdbc implements
        ProprietaireDAO {

    @Override
    public void insertProprietaire(Proprietaire proprietaire)
            throws PrefectureException {
        Connection cx = null;
        PreparedStatement ps = null;
        PreparedStatement ps2 = null;
        ResultSet generatedKeys = null;
        int id;
        try {
            cx = getConnection();
            cx.setAutoCommit(false);
            String sql = "insert into proprietaire ( pro_adresse) values (?)";
            ps = cx.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            ps.setString(1, proprietaire.getAdresse());
            ps.executeUpdate();

            generatedKeys = ps.getGeneratedKeys();
            
            if (generatedKeys.next()) {
                id = generatedKeys.getInt("GENERATED_KEY");

                if (proprietaire instanceof Societe) {
                    try {
                        sql = "insert into societe (soc_pro_id, soc_siret, soc_raison_sociale) values (?,?,?)";
                        ps2 = cx.prepareStatement(sql);
                        ps2.setInt(1, id);
                        ps2.setString(2, ((Societe) proprietaire).getSiret());
                        ps2.setString(3,
                                ((Societe) proprietaire).getRaisonSociale());
                        ps2.executeUpdate();
                    } catch (Exception e) {
                        throw new PrefectureException(
                                "Echec insertion societe", e);
                    }
                } else {
                    try {

                        sql = "insert into particulier (par_pro_id, par_nom, par_prenom) values (?,?,?)";
                        ps2 = cx.prepareStatement(sql);
                        ps2.setInt(1, id);
                        ps2.setString(2, ((Particulier) proprietaire).getNom());
                        ps2.setString(3,
                                ((Particulier) proprietaire).getPrenom());
                        ps2.executeUpdate();
                    } catch (Exception e) {
                        throw new PrefectureException(
                                "Echec insertion particulier", e);
                    }
                }
                cx.commit();
            }
        } catch (Exception e) {
            throw new PrefectureException("Echec insertion proprietaire", e);
        } finally {
            close(cx, ps, ps2);
        }

    }

}
